import {defineStore} from 'pinia'
import {ref,computed} from 'vue'
import {useUserStore} from './userStore.js'
import {insertCartAPI,findNewCartListAPI,deleteCartAPI,mergeCartAPI} from '@/apis/cart.js'

export const useCartStore = defineStore('cart',()=>{
    const userStore=useUserStore();
    const isLogin = computed(()=>userStore.userInfo.token);
    const cartList = ref([]);
    //获取购物车列表
    const updateNewsList =async() =>{
        const res = await findNewCartListAPI();
        cartList.value=res.data.result;
    }
    const addCart = async (goods)=>{
        console.log(isLogin.value);
        if(isLogin.value){
            const {skuId,count} = goods;
            await insertCartAPI({skuId,count})
            updateNewsList();
        }else{
            const item = cartList.value.find((item)=>item.skuId===goods.skuId);
            if(item){
                item.count+=goods.count
            }else{
                cartList.value.push(goods)
            }
        }
       
    }
    const delCart = async(skuId)=>{
        console.log(isLogin.value);
        if(isLogin.value){
            await deleteCartAPI([skuId]);
            updateNewsList();
        }else{
            const idx = cartList.value.findIndex((item)=>item.skuId === skuId)
            cartList.value.splice(idx,1)
        } 
    }

    const clearCart = ()=>{
        cartList.value=[];
    }

    const mergeCart = async()=>{
       await mergeCartAPI(cartList.value.map(item=>{
            return {
                skuId:item.skuId,
                selected:item.selected,
                count:item.count
            }
        }))
    }

    const singleCheck = (skuId,selected)=>{
        const item = cartList.value.find((item)=>item.skuId === skuId)
        item.selected=selected
    }

    const allCheck = (selected)=>{
        cartList.value.forEach((item)=>item.selected=selected)
    }

    // const allCount = computed(()=>{return cartList.value.reduce((a,c)=>{return a+c.count},0)})
    // const allPrice = computed(()=>{return cartList.value.reduce((a,c)=>{return a+c.count * c.price},0)})
    const allCount = computed(()=>cartList.value.reduce((a,c)=>a+c.count,0))
    const allPrice = computed(()=>cartList.value.reduce((a,c)=>a+c.count * c.price,0))
    const isAll = computed(()=>cartList.value.every((item)=>item.selected))
    const selectedCount = computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count,0))
    // const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
    const selectedPrice = computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count*c.price,0))
    return {
        cartList,
        allCount,
        allPrice,
        selectedCount,
        selectedPrice,
        isAll,
        addCart,
        delCart,
        clearCart,
        singleCheck,
        allCheck,
        mergeCart,
        updateNewsList
    }
},{
    persist:true
})